<template>
  <l-layout class="l-tab-page">
    <l-panel>
      <template #toolLeft>
        <l-query2
          :items="queryItems"
          :formData="queryData"
          :loading="tableLoading"
          @search="handleSearch"
          v-if="queryOpen"
        >
          <template #f_CreateDate>
            <el-date-picker
              v-model="queryData.f_CreateDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </template>
          <template #f_State>
            <l-select
              v-model="queryData.f_State"
              :options="erp_case_f_StateOptions"
            />
          </template>
          <template #f_Name>
            <el-input v-model="queryData.f_Name" placeholder="请输入关键字" />
          </template>
        </l-query2>
      </template>

      <template #toolRight>
        <l-tool-btns
          :isAuth="false"
          :hasRefresh="false"
          @setting="lr_handleSettingTable"
          @click="handleAdd()"
        />
      </template>
      <l-table
        ref="mainTable"
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
        :key="tableData.index"
      >
        <l-table-btns
          :isAuth="false"
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        />
      </l-table>
    </l-panel>

    <!--表单-->
    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="formVisible"
      :height="465"
      :width="487"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <supply-list-form
        ref="form"
        :supplierId="supplierId"
        :isReadOnly="formDetails"
      />
    </l-dialog>

    <!-- 历史价格比对 -->
    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="priceVisible"
      :height="465"
      :width="487"
      :hasBtns="false"
      @close="priceCloseForm"
      @opened="priceOpenedForm"
    >
      <l-echarts
        :option="priceOptions"
        ref="echart"
        v-if="priceLoaded"
      ></l-echarts>
    </l-dialog>
  </l-layout>
</template>

<script>
const api = window.$api.erpcase.supplier;
import SupplyListForm from "./supplyListForm";

export default {
  components: {
    SupplyListForm,
  },
  props: {
    isReadOnly: {
      type: Boolean,
      default: false,
    },
    supplierId: String,
  },
  data() {
    return {
      moduleCode: "handle_supplyList",
      queryOpen: false,

      // 图形
      priceVisible: false,
      priceLoaded: false,
      priceOptions: {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          show: false,
        },
        grid: {
          top: "10%",
          bottom: "10%",
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            barMaxWidth: 20, // 每一个都要设置
            barMinWidth: 5, // 每一个都要设置

            name: "历史记录",
            type: "bar",
            emphasis: {
              focus: "series",
            },
            data: [],
            itemStyle: {
              color: "#5E95FF",
            },
          },
        ],
      },

      // 查询参数
      queryData: {
        f_CreateDate: "",
        f_State: "",
        f_Name: "",
      },

      queryItems: [
        { label: "添加时间", prop: "f_CreateDate" },
        { label: "状态", prop: "f_State" },
        { label: "搜索", prop: "f_Name" },
      ],

      // 表格参数
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tableCurrentPage: 1,
      tablePageSize: 50,
      columns: [
        { label: "物料编码", prop: "f_Number", align: "left" },
        { label: "物料名称", prop: "f_Name", align: "left", dataType: "input" },
        {
          label: "规格型号",
          prop: "f_Model",
          align: "left",
          dataType: "input",
        },
        {
          label: "当前采购单价",
          prop: "f_Price",
          align: "left",
          dataType: "input",
        },
        {
          label: "添加时间",
          prop: "f_CreateDate",
          dataType: "datetime",
          format: "yyyy-MM-dd",
        },
        {
          label: "状态",
          prop: "f_State",
          width: 120,
          align: "left",
          dataType: "switch",
          setting: {
            width: 40,
            activeIconClass: "",
            inactiveIconClass: "",
            activeText: "",
            inactiveText: "",
            valueType: "number",
            activeValue: "1",
            inactiveValue: "0",
            activeColor: "#409EFF",
            inactiveColor: "#C0CCDA",
            csType: "int",
            pid: "1670403938708_34398",
            ptype: "card",
          },
        },
        { label: "操作人", prop: "f_ModifyUserName" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑", width: 80 },
        { prop: "Price", label: "历史价格对比" },
        { prop: "Delete", label: "删除" },
      ],

      // 表单参数
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,
      formDetails: false,
    };
  },
  computed: {
    erp_case_f_StateOptions() {
      return [
        { label: "全部", value: "" },
        { label: "启用", value: 1 },
        { label: "未启用", value: 0 },
      ];
    },
  },
  created() {
    this.init();
    // 延时打开
    setTimeout(() => {
      this.queryOpen = true;
    }, 500);
  },
  methods: {
    init() {
      this.loadTableData();
    },
    handleSearch() {
      this.loadTableData();
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = this.$deepClone(this.queryData);

      queryData.rows = this.tablePageSize;
      queryData.page = this.tableCurrentPage;
      queryData.sidx = "F_CreateDate DESC";
      queryData.f_SupplierId = this.supplierId;

      let data = await this.$awaitWraper(api.supplymaterialpage(queryData));
      if (data != null) {
        this.tableData = data.rows;
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
      }
      this.tableLoading = false;
    },

    handleEdit($index, row) {
      this.formEdit = true;
      this.formDetails = false;
      this.formEditRow = row;
      this.handleShowForm("编辑");
    },

    handleDelete($index, row) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(async () => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          await api.removeMaterial(row.f_Id);
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除!"),
          });
        });
    },
    handleAdd() {
      this.formEdit = false;
      this.formDetails = false;
      this.handleShowForm("新增");
    },

    async handleSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      if (await this.$refs.form.validateForm()) {
        // console.log('新增')
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEditRow ? this.formEditRow.f_Id : "",
          isEdit: this.formEdit,
        });
        if (res) {
          const msg = this.formEdit ? "更新成功!" : "新增成功!";
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTableData();
          this.formVisible = false;
        }
      }
      hideLoading();
    },

    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.f_Id });
        hideLoading();
      }
    },
    handleCloseForm() {
      if (this.formTitle != "历史价格对比") {
        this.$refs.form.resetForm();
      }
    },

    async handlePrice($index, row) {
      this.formTitle = "历史价格对比";
      this.formEditRow = row;
      this.priceVisible = true;
    },
    async priceOpenedForm(showLoading, hideLoading) {
      showLoading("加载数据");
      this.priceLoaded = false;
      const data = await this.$awaitWraper(
        api.supplypricelogs({
          f_SupplymaterialId: this.formEditRow.f_Id,
        })
      );
      this.priceOptions.series[0].data = [];
      this.priceOptions.xAxis.data = [];
      if (data) {
        for (let i in data) {
          this.priceOptions.series[0].data.push(data[i].f_CurrentPrice);
          this.priceOptions.xAxis.data.push(
            this.lr_dateFormat(data[i].f_CreateDate)
          );
        }
      }
      this.priceLoaded = true;
      hideLoading();
    },
    priceCloseForm() {
      this.priceVisible = false;
    },
  },
};
</script>
